//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using System.Windows;
using OpenLS.Drawing.UI;
using OpenLS.UI;
using System.Windows.Interop;

namespace OpenLS.Chart.UI
{
    class PropertyHelper
    {
        public static void ShowPropertiesFor(object obj, FrameworkElement caller, string title, PropertyTabHint hint)
        {
            if (BrowserInteropHelper.IsBrowserHosted)
                ShowPropertiesHostedFor(caller, obj, hint);
            else
                showPropertiesNonHostedFor(caller, obj, hint);
        }

        private static void ShowPropertiesHostedFor(FrameworkElement caller, object obj, PropertyTabHint hint)
        {
            var control = new PropertiesControl {DataContext = obj};

            transferProperties(caller, control);

            if (obj is Series)
                SeriesElement.SetSeries(control, (Series)obj);
            ChartElement.SetObjectContext(control, obj);
            PropertyElement.SetPropertyTabHint(control, hint);
            // TODO SJE: fix the lambda
            WindowServices.ShowDialog(control, "", caller, o => { }, o=> true);
            ;
            // (control, null, caller, null);
        }

        private static void showPropertiesNonHostedFor(FrameworkElement caller, object obj, PropertyTabHint hint)
        {
            var w = new PropertiesWindow {Owner = WindowServices.GetAncestor<Window>(caller)};
            FrameworkElement container = w;

            container.DataContext = obj;
            transferProperties(caller, container);
            if (obj is Series)
                SeriesElement.SetSeries(container, (Series)obj);
            ChartElement.SetObjectContext(container, obj);
            PropertyElement.SetPropertyTabHint(container, hint);
            ((Window)container).ShowDialog();
        }

        private static void transferProperties(FrameworkElement caller, FrameworkElement container)
        {
            foreach (DependencyProperty property in tranferProperties)
            {
                transferProperty(container, caller, property);
            }
        }

        static IEnumerable<DependencyProperty> tranferProperties
        {
            get
            {
                yield return ChartElement.ChartAreaProperty;
                yield return ChartElement.ChartProperty;
                yield return ChartElement.PlotAreaProperty;
                yield return SeriesElement.SeriesProperty;
                yield return DrawingElement.ThemeProperty;
                yield return DrawingElement.ColorSchemeProperty;
            }
        }
        static void transferProperty (FrameworkElement target, FrameworkElement source, DependencyProperty property)
        {
            target.SetValue(property, source.GetValue(property));
        }
    }
}
